package com.imooc.apigateway.filter;

import com.imooc.apigateway.utils.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/** 权限拦截（区分买家和卖家）
 * @author Jiayuan
 * @version 1.0
 * @description:
 * @time 11/8/2018 7:13 PM
 */

@Component
public class AuthSellerrFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if("/order/order/finish".equals(request.getRequestURL())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() {
        /**
         *  /order/create 只能买家访问（cookie里有openId）
         *  /order/finish  只能卖家访问（cookie里有token，并且对应的redis中值相等)
         *  /product/list 都可访问
         */
        //这里从url参数里获取，也可以从cookie,header里获取
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
            Cookie cookie = CookieUtil.get(request,"token");
            if(cookie == null || StringUtils.isEmpty(cookie.getValue())){
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            }
        return null;
    }
}
